#include <iostream>
#include <pthread.h>
#include <sqlite3.h>
#include <jsoncpp/json/json.h>
#include <sys/stat.h>
#include <ndn-cxx/util/io.hpp>
#include <ndn-cxx/security/signing-helpers.hpp>
#include <ndn-cxx/security/verification-helpers.hpp>
#include <ndn-cxx/security/transform.hpp>
#include <ndn-cxx/encoding/buffer-stream.hpp>

static int execSQL(const std::string &sql){
	std::string homePath = getenv("HOME") ;
	std::string certTable = homePath + "/.ndn/certs.db" ;
	sqlite3 *sqliteDB  ;
	int execRet = 0 ;
	if(access(certTable.data(), F_OK) != 0){
		execRet = sqlite3_open(certTable.data(), &sqliteDB) ;
		std::string createTableSql = "CREATE TABLE cert (name text primary key not NULL, value text not NULL)" ;
		execRet = sqlite3_exec(sqliteDB, createTableSql.data(), 0, 0, NULL) ;
	}else{
		execRet = sqlite3_open(certTable.data(), &sqliteDB) ;
	}
	execRet = sqlite3_exec(sqliteDB, sql.data(), 0, 0, NULL) ;
	sqlite3_close(sqliteDB) ;
	return execRet ;
}


static bool isValidBlock(const std::string& str){
	namespace t = ndn::security::transform;
	try{
		ndn::OBufferStream os;
		std::istringstream is(str) ;
		t::streamSource(is) >> t::stripSpace("\n") >> t::base64Decode(false)
			>> t::streamSink(os);
		Block b(os.buf()) ;
	}catch(...){
		return false ;
	}
	return true ;
}

// 返回值为0才表示执行成功
static int installCert(const std::string &certStr) {
	if(!isValidBlock(certStr)) return -1 ;
	std::stringstream ss(certStr) ;
	ndn::security::v2::Certificate cert =
		*(ndn::io::load<ndn::security::v2::Certificate>(ss)) ;
	std::string sql = "insert into cert (name, value) values ('" ;
	sql = sql + cert.getName().toUri() + "','"+ certStr +"')" ;
	int execRet = execSQL(sql) ;

	return execRet ;
}

int main()
{
	std::string certStr = "Bv0CNAc0CAN3Z2gICGlkZW50aXR5CAMwMDEIA0tFWQgIufOJCbAg8pUIBHNlbGYICf0AAAFuQ4UeSxQJGAECGQQANu6AFf0BTzCCAUswggEDBgcqhkjOPQIBMIH3AgEBMCwGByqGSM49AQECIQD/////AAAAAQAAAAAAAAAAAAAAAP///////////////zBbBCD/////AAAAAQAAAAAAAAAAAAAAAP///////////////AQgWsY12Ko6k+ez671VdpiGvGUdBrDMU7D2O848PifSYEsDFQDEnTYIhucEk2pmeOETnSa3gZ9+kARBBGsX0fLhLEJH+Lzm5WOkQPJ3A32BLeszoPShOUXYmMKWT+NC4v4af5uO5+tKfA+eFivOM1drMV7Oy7ZAaDe/UfUCIQD/////AAAAAP//////////vOb6racXnoTzucrC/GMlUQIBAQNCAAQgBY7APn653aEYEhlCMdCOvF0xt7/PTjMj/w3jUzhR7mJQxf2JfLiIUUvIPVdOMMDthfLMDwNaZpV8dqBG9k4kFlQbAQMcJQcjCAN3Z2gICGlkZW50aXR5CAMwMDEIA0tFWQgIufOJCbAg8pX9AP0m/QD+DzE5NzAwMTAxVDAwMDAwMP0A/w8yMDM5MTEwMlQwMTQwMjcXSDBGAiEAip/n+goaJUhTv4HG6jAihRW2dP0x+HE6oKfbyl+J+cUCIQCzvOtnOX8q3tWsU+sxI3/q/pxGaluE14D+8og+WBm6fw==" ;
	int ret = installCert(certStr) ;
	std::cout << "result = " << ret << std::endl ;
	return 0;
}
